package com.fhnew.app.ui.activity.userinfo.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.model.ThirdGameModel;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;

import com.fhnew.app.model.network.entity.req.ResALLGames;
import com.fhnew.app.model.network.entity.req.ResChangemoney;
import com.fhnew.app.model.network.entity.req.ResgetMoney;
import com.fhnew.app.model.network.entity.req.Resmsg;

import com.fhnew.app.util.OnItemClickListener;
import com.fhnew.app.util.SYSOUtils;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/9/12.
 */

public class ChangemoneyFragment extends Fragment {

    private TextView moneynum;
    private TextView balance;
    private NiceSpinner spinner;
    private RecyclerView leftlist;
    private TextView changename;
    private RecyclerView rightlist;
    private EditText changeet;
    private TextView changebt;
    private TextView cahngeclear;
    private Adapter adapter;
    private Adapter1 adapter1;
    private ArrayList<ResALLGames.DataBean> usergamedata = new ArrayList<>();
    private ArrayList<ResALLGames.DataBean> usergamedata1 = new ArrayList<>();//spinner专用
    private int rightpostion = -1;
    private String rightname = "某某";
    private int leftpostion = -1;
    private String leftname = "某某";
    private String leftid;
    private String rightid;


    private void initView (View view) {
        moneynum = view.findViewById(R.id.moneynum);
        balance = view.findViewById(R.id.balance);
        spinner = view.findViewById(R.id.spinner);
        leftlist = view.findViewById(R.id.leftlist);
        changename = view.findViewById(R.id.changename);
        rightlist = view.findViewById(R.id.rightlist);
        changeet = view.findViewById(R.id.changeet);
        changebt = view.findViewById(R.id.changebt);
        cahngeclear = view.findViewById(R.id.cahngeclear);

        changename.setOnClickListener(onClickListener);
        changeet.setOnClickListener(onClickListener);
        changebt.setOnClickListener(onClickListener);
        cahngeclear.setOnClickListener(onClickListener);
    }



    @Nullable
    @Override
    public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        container = (ViewGroup) inflater.inflate(R.layout.changemoneylayout, null);
        initView(container);
        init();
        return container;
    }

    @Override
    public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getusergamedata();
        moneynum.setText(UserModel.user.money);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        leftlist.setLayoutManager(linearLayoutManager);
        adapter = new Adapter();
        leftlist.setAdapter(adapter);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getContext());
        rightlist.setLayoutManager(linearLayoutManager1);
        adapter1 = new Adapter1();
        rightlist.setAdapter(adapter1);

        spinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected (NiceSpinner parent, View view, int position, long id) {
                getBalance(usergamedata1.get(position).game_id);
            }
        });
    }

    @Override
    public void onDestroy () {
        super.onDestroy();
        thirdGameModel.unregistThirdGameMoneyChangedListener(thirdGameMoneyChangedListener);
    }

    private ThirdGameModel.ThirdGameMoneyChangedListener thirdGameMoneyChangedListener = new ThirdGameModel.ThirdGameMoneyChangedListener() {
        @Override
        public void myMoneyChanged () {
            moneynum.setText(userModel.getUser().getMoney());
        }

        @Override
        public void allThirdGameMoneyChanged () {

        }

        @Override
        public void thirdGameMoneyChanged (int game_id) {

        }
    };

    //====================================================================
    //
    //====================================================================
    private ThirdGameModel thirdGameModel;
    private UserModel userModel;
    private void init(){
        userModel = UserModel.getInstance(getContext());

        thirdGameModel = ThirdGameModel.getInstance(getContext());
        thirdGameModel.registThirdGameMoneyChangedListener(thirdGameMoneyChangedListener);
    }



    //====================================================================
    //
    //====================================================================

    //获取平台余额
    private void getBalance (int game_id) {
        HttpJsonUtils.getHttpApiInstance()
                .getaction(Constants.getuseAdress() + "api/GamesApi/action", 1 + "", game_id + "", UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<Resmsg>(ChangemoneyFragment.this) {
                .subscribe(new CustomObserver<Resmsg>() {
                    @Override
                    protected void onCustomNext (Resmsg resmsg) {
                        balance.setText(resmsg.data.money);
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });

    }

//    private void getmoney () {
//        HttpJsonUtils.getHttpApiInstance()
//                .getMoney(Constants.getuseAdress() + "api/m/user/getMoney", UserModel.Token)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
////                .subscribe(new CustomObserver<ResgetMoney>(ChangemoneyFragment.this) {
//                .subscribe(new CustomObserver<ResgetMoney>() {
//                    @Override
//                    protected void onCustomNext (ResgetMoney resActivity) {
//                        if (resActivity.code == 0) {
//                            UserModel.user.money = resActivity.data.balance;
//                            moneynum.setText(resActivity.data.balance);
//                        }
//                    }
//
//                    @Override
//                    protected void onSubscribeCustom (Disposable disposable) {
//                    }
//
//                    @Override
//                    protected void onErrorCustom (Throwable e) {
//
//                    }
//                });
//    }

    //获取平台列表
    private void getusergamedata () {
        HttpJsonUtils.getHttpApiInstance()
                .getallgame(Constants.getuseAdress() + "api/GamesApi/list_2", UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<ResALLGames>(ChangemoneyFragment.this) {
                .subscribe(new CustomObserver<ResALLGames>() {
                    @Override
                    protected void onCustomNext (ResALLGames resALLGames) {
                        if (resALLGames.code == 0) {
                            saveallgame(resALLGames.data);
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            switch (view.getId()) {
                case R.id.changename:

                    break;
                case R.id.changeet:
                    break;
                case R.id.changebt:
                    if (!TextUtils.isEmpty(leftid) && !TextUtils.isEmpty(rightid) && !TextUtils.isEmpty(changeet.getText().toString().trim())) {
                        changemoney();
                    } else {
                        Toast.makeText(getContext(), "请补全信息", Toast.LENGTH_LONG).show();
                    }
//                hideKeyboard(getContext());
                    break;
                case R.id.cahngeclear:
                    Sign_out_game();
                    break;
            }
        }
    };


    private void Sign_out_game () {
        HttpJsonUtils.getHttpApiInstance()
                .Sign_out_game(Constants.getuseAdress() + "api/GamesApi/allDown", UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<Resmsg>(ChangemoneyFragment.this) {
                .subscribe(new CustomObserver<Resmsg>() {
                    @Override
                    protected void onCustomNext (Resmsg resmsg) {
                        if (resmsg.code == 0) {
                            Toast.makeText(getContext(), "回收成功", Toast.LENGTH_SHORT).show();
//                            getmoney();
                        } else {
                            Toast.makeText(getContext(), resmsg.msg + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });
    }

    //额度转换
    private void changemoney () {
        HttpJsonUtils.getHttpApiInstance()
                .changemoney(Constants.getuseAdress() + "api/GamesApi/moneyExchange_2",
                        leftid, rightid, changeet.getText().toString().trim(), UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<ResChangemoney>(ChangemoneyFragment.this) {
                .subscribe(new CustomObserver<ResChangemoney>() {
                    @Override
                    protected void onCustomNext (ResChangemoney resALLGames) {
                        if (resALLGames.code == 0) {
                            Toast.makeText(getContext(), "转换成功", Toast.LENGTH_LONG).show();
                            moneynum.setText(resALLGames.data.uMoney);
                            UserModel.user.money = resALLGames.data.uMoney;
                        } else {
                            Toast.makeText(getContext(), "" + resALLGames.msg, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });
    }

    /////////////////////////////////////left//////////////////////////////////////////////
    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @NonNull
        @Override
        public Adapter.MViewHolder onCreateViewHolder (@NonNull ViewGroup viewGroup, int viewType) {
            return new Adapter.MViewHolder(LayoutInflater.from(getContext())
                    .inflate(R.layout.textitem, viewGroup, false));
        }

        @Override
        public void onBindViewHolder (final Adapter.MViewHolder holder, final int position) {
            holder.textitem.setTextColor(getContext().getResources().getColor(R.color.moccasin));
            if (position == 0) {
                holder.textitem.setText("我的钱包");
            } else {
                holder.textitem.setText(usergamedata.get(position).name);
            }
            if (leftpostion != -1 && leftpostion == position) {
                holder.textitem.setBackgroundResource(R.color.btbackground);
            } else {
                holder.textitem.setBackgroundResource(R.mipmap.settingbt);
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick (View v) {
                    leftpostion = position;
                    if (position == 0) {
                        leftname = "我的钱包";
                        leftid = "0";
                    } else {
                        leftname = usergamedata.get(position).name;
                        leftid = usergamedata.get(position).game_id + "";
                    }
                    adapter.notifyDataSetChanged();
                    changename.setText("确认从" + leftname + "转账至" + rightname + "平台吗?");

                }
            });
        }

        @Override
        public int getItemCount () {
            return usergamedata.size();

        }

        @Override
        public void onItemClick (View view, int position) {

        }

        public class MViewHolder extends RecyclerView.ViewHolder {
            TextView textitem;

            MViewHolder (View itemView) {
                super(itemView);
                textitem = (TextView) itemView.findViewById(R.id.textitem);
            }
        }
    }

    /////////////////////////////////////right////////////////////////////////////////
    class Adapter1 extends RecyclerView.Adapter<Adapter1.MViewHolder1>
            implements OnItemClickListener {
        @NonNull
        @Override
        public Adapter1.MViewHolder1 onCreateViewHolder (@NonNull ViewGroup viewGroup, int viewType) {
            return new Adapter1.MViewHolder1(LayoutInflater.from(getContext())
                    .inflate(R.layout.textitem, viewGroup, false));
        }

        @Override
        public void onBindViewHolder (@NonNull MViewHolder1 holder, int position) {
            holder.textitem.setTextColor(getContext().getResources().getColor(R.color.moccasin));
            if (position == 0) {
                holder.textitem.setText("我的钱包");
            } else {
                holder.textitem.setText(usergamedata.get(position).name);
            }
            if (rightpostion != -1 && rightpostion == position) {
                holder.textitem.setBackgroundResource(R.color.btbackground);
            } else {
                holder.textitem.setBackgroundResource(R.mipmap.settingbt);
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick (View v) {
                    if (position == 0) {
                        rightname = "我的钱包";
                        rightid = "0";
                    } else {
                        rightname = usergamedata.get(position).name;
                        rightid = usergamedata.get(position).game_id + "";
                    }
                    rightpostion = position;
                    adapter1.notifyDataSetChanged();
                    changename.setText("确认从" + leftname + "转账至" + rightname + "平台吗?");

                }
            });
        }

        @Override
        public int getItemCount () {
            return usergamedata.size();

        }

        @Override
        public void onItemClick (View view, int position) {

        }

        public class MViewHolder1 extends RecyclerView.ViewHolder {
            TextView textitem;

            MViewHolder1 (View itemView) {
                super(itemView);
                textitem = (TextView) itemView.findViewById(R.id.textitem);
            }
        }
    }

    public void saveallgame (List<ResALLGames.DataBean> data) {
        LinkedList<String> data1 = new LinkedList<>();
        data1.clear();
        for (int i = 0; i < data.size(); i++) {
            data1.add(data.get(i).name);
        }
        spinner.attachDataSource(data1);
        usergamedata.clear();
        for (int i = 0; i < data.size() + 1; i++) {
            if (i == 0) {
                usergamedata.add(data.get(0));
            } else {
                usergamedata.add(data.get(i - 1));
            }
        }
        usergamedata1.clear();
        usergamedata1.addAll(data);
        SYSOUtils.sOut_("得到++++++++++++++++++++++++++++++++++++++了什么" + usergamedata);
        adapter.notifyDataSetChanged();
    }

    public static void hideKeyboard (Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void getMoney () {
        HttpJsonUtils.getHttpApiInstance()
                .getMoney(Constants.getuseAdress() + "api/m/user/getMoney", UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<ResgetMoney>(ChangemoneyFragment.this) {
                .subscribe(new CustomObserver<ResgetMoney>() {
                    @Override
                    protected void onCustomNext (ResgetMoney resActivity) {
                        if (resActivity.code == 0) {
                            SYSOUtils.sOut_("游戏余额===========================================" + resActivity.data.balance);
                            UserModel.user.money = resActivity.data.balance;
                            moneynum.setText(UserModel.user.money);
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });
    }

}
